<template>
    <div>
        <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>商品管理</el-breadcrumb-item>
        <el-breadcrumb-item>分类参数</el-breadcrumb-item>
        </el-breadcrumb>
        <el-card>
            <el-alert
                title="注意：只允许为第三级分类设置相关参数！"
                type="warning"
                show-icon
                :closable="false">
            </el-alert>
            <el-row class="cat_opt">
                <el-col>
                    <span>选择商品分类：</span>
                    <!-- 级联选择框 -->
                    <el-cascader
                    v-model="selectedCatKeys"
                    :options="cateList"
                    :props="cateProps"
                    @change="handleChange">
                    </el-cascader>
                </el-col>
            </el-row>
            <!-- tab页组件 -->
            <el-tabs v-model="activeName" @tab-click="handleTabClick">
                <!-- 动态参数面板 -->
                <el-tab-pane label="动态参数" name="many">
                    <el-button type="primary" size="mini" :disabled='isBtnDisble' @click="showAddParmsDialog">添加参数</el-button>
                    <el-table :data="manyTableData" border>
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template  slot-scope="scope">
                              <!-- 循环渲染tag标签 -->
                            <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i"  closable @close="tagClosed(i,scope.row)">{{item}}</el-tag>
                            <!-- 输入标签框 -->
                            <el-input
                              class="input-new-tag"
                              v-if="scope.row.inputVisible"
                              v-model="scope.row.inputValue"
                              ref="saveTagInput"
                              size="small"
                              @keyup.enter.native="handleInputConfirm(scope.row)"
                              @blur="handleInputConfirm(scope.row)">
                            </el-input>
                            <!-- 点击新增标签 -->
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParmsDialog(scope.row.attr_id)">编辑</el-button>
                                  <template>
                                    <el-popconfirm @onConfirm="removeParams(scope.row.attr_id)"
                                      title="确定删除该参数吗？">
                                      <el-button size="mini" type="danger" icon="el-icon-delete" slot="reference">删除</el-button>
                                    </el-popconfirm>
                                  </template>
                                  <!-- <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button> -->
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
                <!-- 静态属性面板 -->
                <el-tab-pane label="静态属性" name="only">
                    <el-button type="primary" size="mini" :disabled='isBtnDisble' @click="showAddParmsDialog">添加属性</el-button>
                                        <el-table :data="onlyTableData" border="">
                        <!-- 展开行 -->
                        <el-table-column type="expand">
                            <template  slot-scope="scope">
                              <!-- 循环渲染tag标签 -->
                            <el-tag v-for="(item,i) in scope.row.attr_vals" :key="i"  closable @close="tagClosed(i,scope.row)">{{item}}</el-tag>
                            <!-- 输入标签框 -->
                            <el-input
                              class="input-new-tag"
                              v-if="scope.row.inputVisible"
                              v-model="scope.row.inputValue"
                              ref="saveTagInput"
                              size="small"
                              @keyup.enter.native="handleInputConfirm(scope.row)"
                              @blur="handleInputConfirm(scope.row)">
                            </el-input>
                            <!-- 点击新增标签 -->
                            <el-button v-else class="button-new-tag" size="small" @click="showInput(scope.row)">+ New Tag</el-button>
                            </template>
                        </el-table-column>
                        <el-table-column type="index"></el-table-column>
                        <el-table-column label="参数名称" prop="attr_name"></el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                  <el-button size="mini" type="primary" icon="el-icon-edit" @click="showEditParmsDialog(scope.row.attr_id)">编辑</el-button>
                                  <template>
                                    <el-popconfirm @onConfirm="removeParams(scope.row.attr_id)"
                                      title="确定删除该参数吗？">
                                      <el-button size="mini" type="danger" icon="el-icon-delete" slot="reference">删除</el-button>
                                    </el-popconfirm>
                                  </template>
                                  <!-- <el-button size="mini" type="danger" icon="el-icon-delete">删除</el-button> -->
                            </template>
                        </el-table-column>
                    </el-table>
                </el-tab-pane>
            </el-tabs>
        </el-card>
        <!-- 添加动态参数|静态属性对话框 -->
        <el-dialog
          :title="'添加'+ titleText"
          :visible.sync="addParamsDialogVisible"
          width="50%" @close="addParamsDialogClosed">
          <el-form :model="addParamsForm" :rules="addParamsRules" ref="addParamsRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
              <el-input v-model="addParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="addParamsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="addParams">确 定</el-button>
          </span>
        </el-dialog>

                <!-- 修改动态参数|静态属性对话框 -->
        <el-dialog
          :title="'修改'+ titleText"
          :visible.sync="editParamsDialogVisible"
          width="50%" @close="editParamsDialogClosed">
          <el-form :model="editParamsForm" :rules="editParamsRules" ref="editParamsRef" label-width="100px">
            <el-form-item :label="titleText" prop="attr_name">
              <el-input v-model="editParamsForm.attr_name"></el-input>
            </el-form-item>
          </el-form>
          <span slot="footer" class="dialog-footer">
            <el-button @click="editParamsDialogVisible = false">取 消</el-button>
            <el-button type="primary" @click="editParams">确 定</el-button>
          </span>
        </el-dialog>
    </div>
</template>
<script>
export default {
  data () {
    return {
      cateList: [],
      cateProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover'
      },
      selectedCatKeys: [],
      //   被激活的tab页
      activeName: 'many',
      // 动态参数表数据
      manyTableData: [],
      // 静态属性表数据
      onlyTableData: [],
      // 添加参数对话框
      addParamsDialogVisible: false,
      // 添加参数表单数据
      addParamsForm: {
        attr_name: ''
      },
      // 添加参数的表单验证规则
      addParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      },
      // 添加参数对话框
      editParamsDialogVisible: false,
      // 修改参数表单数据
      editParamsForm: {
      },
      // 修改参数的表单验证规则
      editParamsRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' }
        ]
      }
    }
  },
  created () {
    this.getCateList()
  },
  methods: {
    // 获取商品分类列表
    async getCateList () {
      const { data: res } = await this.$http.get('categories')
      if (res.meta.status !== 200) {
        return this.$message.error('获取商品分类失败！')
      }
      // 给数据列表赋值
      this.cateList = res.data
    },
    // 级联选择器选中节点时
    handleChange () {
    //   console.log(this.selectedCatKeys)
      if (this.selectedCatKeys.length !== 3) {
        this.selectedCatKeys = []
        this.manyTableData = []
        this.onlyTableData = []
        return this.$message.error('请选择三级分类')
      } else { this.getParamsDate() }
    },
    // tab页按钮被点击时
    handleTabClick () {
    //   console.log(this.activeName)
      this.getParamsDate()
    },
    // 获取商品参数数据
    async getParamsDate () {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes`, { params: { sel: this.activeName } })
      if (res.meta.status !== 200) return this.$message.error('获取参数数据失败')
      //   console.log(res.data)
      //   把数据的attr_vals字符串变为数组
      res.data.forEach(item => {
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 添加一个控制添加tag 按钮 与文本框的切换
        item.inputVisible = false
        // 文本框输入的值
        item.inputValue = ''
      })
      // 判断tab页的类型。然后赋值给对应的列表
      if (this.activeName === 'many') {
        this.manyTableData = res.data
      } else { this.onlyTableData = res.data }
    },
    // 点击添加tag标签之后显示输入框
    showInput (row) {
      row.inputVisible = true
      // $nextTick等待页面被重新渲染之后执行函数
      this.$nextTick(_ => {
        // 使输入框自动获取焦点
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 输入框失去焦点或者按下Enter 触发
    async handleInputConfirm (row) {
      if (row.inputValue.trim().length === 0) {
        row.inputValue = ''
        row.inputVisible = false
        return
      }
      // 如果输入的字符合法进行后续操作
      // console.log(row.inputValue)
      row.attr_vals.push(row.inputValue.trim())
      row.inputVisible = false
      this.saveAttrVals(row)
    },
    // 将attr_vals 的操作提交至数据库
    async saveAttrVals (row) {
      const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${row.attr_id}`,
        { attr_name: row.attr_name, attr_sel: row.attr_sel, attr_vals: row.attr_vals.join(' ') })
      if (res.meta.status !== 200) return this.$message.error('修改参数项失败')
      this.$message.success('添加参数项成功')
    },
    // tag监听关闭事件
    tagClosed (i, row) {
      row.attr_vals.splice(i, 1)
      this.saveAttrVals(row)
    },
    // 显示添加参数对话框
    showAddParmsDialog () {
      this.addParamsDialogVisible = true
    },
    // 监听添加参数对话框的关闭事件
    addParamsDialogClosed () {
      this.$refs.addParamsRef.resetFields()
    },
    // 点击确定添加参数
    addParams () {
      this.$refs.addParamsRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post(`categories/${this.cateId}/attributes`, {
          attr_name: this.addParamsForm.attr_name,
          attr_sel: this.activeName
        })
        console.log(res.data.attr_id)
        if (res.meta.status !== 201) return this.$message.error('添加参数失败')
        this.$message.success('添加参数成功')
        this.addParamsDialogVisible = false
        this.getParamsDate()
      })
    },
    // 显示修改参数对话框,获取当前参数信息
    async showEditParmsDialog (attrId) {
      const { data: res } = await this.$http.get(`categories/${this.cateId}/attributes/${attrId}`, { params: { attr_sel: this.activeName } })
      if (res.meta.status !== 200) return
      this.editParamsForm = res.data
      this.editParamsDialogVisible = true
    },
    // 监听修改参数对话框的关闭事件
    editParamsDialogClosed () {
      this.$refs.editParamsRef.resetFields()
      this.editParamsForm = {}
    },
    // 点击确定修改参数
    editParams () {
      this.$refs.editParamsRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.put(`categories/${this.cateId}/attributes/${this.editParamsForm.attr_id}}`, {
          attr_name: this.editParamsForm.attr_name,
          attr_sel: this.activeName
        })
        // console.log(res.data)
        if (res.meta.status !== 200) return this.$message.error('修改参数失败')
        this.$message.success('修改参数成功')
        this.editParamsDialogVisible = false
        this.getParamsDate()
      })
    },
    // 删除参数名称
    async removeParams (AttrId) {
      const { data: res } = await this.$http.delete(`categories/${this.cateId}/attributes/${AttrId}`)
      if (res.meta.status !== 200) return this.$message.error('删除参数失败')
      this.$message.success('删除参数成功')
      this.getParamsDate()
    }
  },
  computed: {
    // 计算属性
    // 设置按钮是否可用
    isBtnDisble () {
      if (this.selectedCatKeys.length !== 3) return true
      else return false
    },
    // 计算传入的分类id
    cateId () {
      if (this.selectedCatKeys.length === 3) {
        return this.selectedCatKeys[2]
      } else {
        return null
      }
    },
    titleText () {
      if (this.activeName === 'many') {
        return '动态参数'
      } else {
        return '静态属性'
      }
    }
  }
}

</script>
<style lang="less" scoped>
.cat_opt{
    margin-top: 15px;
}
.el-cascader{
    width: 300px;
}
.el-tag{
    margin: 10px;
}
.input-new-tag{
  width: 120px;
}
.el-button{
  margin-right: 10px;
}
</style>
